package com.atguigu.gulimallcart.Interceptor;

import com.atguigu.common.vo.MemberRsepVo;
import com.atguigu.gulimallcart.contant.CartConstant;
import com.atguigu.gulimallcart.vo.UserInfoTo;
import org.springframework.beans.BeanUtils;
import org.springframework.lang.Nullable;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

public class CarInterceptor implements HandlerInterceptor {
    public static ThreadLocal<UserInfoTo> threadLocal=new ThreadLocal<>();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        int a=1;
        MemberRsepVo loginUser = (MemberRsepVo) request.getSession().getAttribute("loginUser");
        UserInfoTo userInfoTo=new UserInfoTo();
        if(loginUser!=null){
            userInfoTo.setUserId(loginUser.getId());
            userInfoTo.setUsername(loginUser.getNickname());
        }
        Cookie[] cookies = request.getCookies();
        if(cookies != null && cookies.length > 0){
            for (Cookie c:cookies) {
                if(c.getName().equals("user_key")){
                    userInfoTo.setUserKey(c.getValue());
                    userInfoTo.setTempUser(true);
                    break;
                }
            }
        }

        if(StringUtils.isEmpty(userInfoTo.getUserKey())){
            String uuid = UUID.randomUUID().toString().replace("-","");
            userInfoTo.setUserKey(uuid);
        }
        threadLocal.set(userInfoTo);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
        UserInfoTo userInfoTo=threadLocal.get();
        if(!userInfoTo.getTempUser()){
            Cookie cookie=new Cookie("user_key",userInfoTo.getUserKey());
            cookie.setDomain("gulimall.com");
            cookie.setMaxAge(CartConstant.TIME_OUT);
            response.addCookie(cookie);
        }
    }


}
